﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Microtalk.Data;
using Microtalk.Models;
using Microtalk.ParamModel;
using Newtonsoft.Json;

namespace Microtalk.Controllers
{
    public class UsersController : Controller
    {
        private MicrotalkContext db = new MicrotalkContext();

        // GET: Users
        public ActionResult Index()
        {
          
                return View(db.Users.ToList());

        }

        // GET: /Users/Login

        public ActionResult Login()
        {
            //获取所有用户
            var userList = db.Users.ToList();

            if (Session["UserName"] == null)
            {
                return View();
            }
            else
            {
                //获取当前用户id
                var cuuentId = userList.SingleOrDefault(x => x.UserName == Session["UserName"].ToString()).Id;

                return RedirectToAction("index/" + cuuentId, "messages");


            }
        }


        // GET: /Users/Register
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]

        public string  LoginDone(ParamLogin login)
        {
            dynamic result;

            if (login.Username.Trim().Length > 0 && login.Password.Trim().Length > 0)
            {
                var user = db.Users.Where(x => x.UserName.Equals(login.Username.Trim()) && x.PassWord.Equals(login.Password.Trim())).FirstOrDefault();

                if (user != null)
                {
                    Session["UserName"] = login.Username;

                    var userList = db.Users.ToList();

                    //获取当前用户id
                    var cuuentId = userList.SingleOrDefault(x => x.UserName == Session["UserName"].ToString()).Id;

                    result = new
                    {
                        cuuentnewId = cuuentId,
                        code = 200,
                        msg = "登录成功"
                    };
                }
                else
                {
                    result = new
                    {
                       code = 1000,
                        msg = "用户名或密码不正确，请核对后重试"
                    };
                }
            }
            else
            {
                result = new
                {
                    code = 1000,
                    msg = "用户名密码不能为空，请核对后重试=_="
                };
            }

            return JsonConvert.SerializeObject(result);
        }


        public string registerDone(ParamRegister register )
        {
            var username = register.Username.Trim();
            var password = register.Password.Trim();
            var againpassword = register.Confirmpassword.Trim();

            dynamic result;

            if(username.Length>0 &&password.Length>0 && password == againpassword)
            {
                var UserDemo = db.Users.Where(x => x.UserName == username).FirstOrDefault();

                //UserDemo不为空表示已经注册该用户
                if( UserDemo != null)
                {
                    result = new
                    {
                      code = 1000,
                      msg = "该账号已经被注册(^o^)/~"
                    };

                }
                else
                {
                    db.Users.Add(new Users
                    {
                        UserName = username,
                        PassWord = password


                    });
                    
                    db.SaveChanges();

                  

                    result = new
                    {
                      
                        code = 200,
                        msg = "登录成功"
                    };

                }

            }
            else
            {
                result = new
                {
                code = 1000,
                msg = "用户名或密码不能为空,并且两次密码必须一致"
                };

            }

            return JsonConvert.SerializeObject(result);
        }

        public string Logout()
        {
            dynamic result;

            Session["UserName"] = null ;

            result = new 
            {
             code =200 ,
             msg ="注销成功"
            };
            return JsonConvert.SerializeObject(result);

        }

        //public string  Say()
        //{

        //    dynamic result;


        //}



        // GET: Users/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Users users = db.Users.Find(id);
            if (users == null)
            {
                return HttpNotFound();
            }
            return View(users);
        }

        // GET: Users/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Users/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        // 更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,UserName,PassWord,CreateAt,UpdateAt,Version,Remarks")] Users users)
        {
            if (ModelState.IsValid)
            {
                db.Users.Add(users);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(users);
        }

        // GET: Users/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Users users = db.Users.Find(id);
            if (users == null)
            {
                return HttpNotFound();
            }
            return View(users);
        }

        // POST: Users/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        // 更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,UserName,PassWord,CreateAt,UpdateAt,Version,Remarks")] Users users)
        {
            if (ModelState.IsValid)
            {
                db.Entry(users).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(users);
        }

        // GET: Users/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Users users = db.Users.Find(id);
            if (users == null)
            {
                return HttpNotFound();
            }
            return View(users);
        }

        // POST: Users/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Users users = db.Users.Find(id);
            db.Users.Remove(users);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }


     
    }
}
